import time
import hmac
import hashlib
import base64
from threading import Timer
from typing import Optional

class XfyunTokenManager:
    def __init__(self, appid: str, api_secret: str, api_key: str):
        self.appid = appid
        self.api_secret = api_secret
        self.api_key = api_key
        self.current_token: Optional[str] = None
        self.token_expire_time: int = 0
        self.refresh_interval = 23 * 3600


        self.generate_token()
        self.start_auto_refresh()

    def generate_token(self) -> str:
        ts = str(int(time.time()))

        signature_origin = self.api_key + ts
        hmac_obj = hmac.new(
            self.api_secret.encode("utf-8"),
            signature_origin.encode("utf-8"),
            hashlib.sha256
        )
        signa = base64.b64encode(hmac_obj.digest()).decode("utf-8")

        token = f"appid={self.appid},ts={ts},signa={signa}"

        self.current_token = token
        self.token_expire_time = int(time.time()) + 86400
        print(f"Token刷新成功！有效期至：{time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(self.token_expire_time))}")
        return token

    def get_token(self) -> str:
        if not self.current_token or int(time.time()) >= self.token_expire_time:
            return self.generate_token()
        return self.current_token

    def start_auto_refresh(self):
        def refresh():
            self.generate_token()

            self.start_auto_refresh()


        Timer(self.refresh_interval, refresh).start()


APPID = "16658f23"
APISecret = "NGYxNGI3YTU1NzU0ODYyMzc5MmNhMTU4"
APIKey = "4a5eb1a92a0a9d60d3e6b6bde60d9bf9"



token_manager = XfyunTokenManager(APPID, APISecret, APIKey)


def call_xfyun_api():
    token = token_manager.get_token()
    headers = {
        "Authorization": token,
        "Content-Type": "application/json"
    }

    print(f"当前使用的Token：{token[:50]}...")


if __name__ == "__main__":
    while True:
        call_xfyun_api()
        time.sleep(3600)
